var isMobile = ismobile();

//$(function () {

var totalPrice, useCoupon, token, address;

//getOrderId();
//nextAjax({
//    "uid": 30,
//    "goods_id": 6,
//    "meal": {"name": "卡卡卡", "data_type": "2388", "id": 0, "goods_worth": 2000},
//    "startTime": "2017-12-27 12:30",
//    "endTime": "2017-12-27 16:30",
//    "number": 2,
//    "money": "4500"
//})
//});

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallTerMinalListModel.postMessage(message);
}

if (isMobile == 0) {

    window.android.getAndroidOrderId("okok");
}

function getOrderId() {

    if (isMobile == 1) {

        CallTerMinalListModel.jsCallOCWithSendId();

    } else if (isMobile == 0) {

        window.android.getAndroidOrderId("okok");
    }
}

function receive_android_orderId(k) {

    var obj = $.parseJSON(k);

    address = obj.need_addr;

    token = obj.TOKEN;

    nextAjax(obj, token, address);

    totalPrice = obj.money;

    useCoupon = 100;
}

function receiveiOSVcData(i) {

    var obj = $.parseJSON(i);

    token = obj.TOKEN;

    address = obj.need_addr;

    nextAjax(obj, token, address);

    totalPrice = obj.money;

    useCoupon = 100;
}

function nextAjax(data_json, token, address) {

    $.ajax({

        type: "POST",

        url: url + "users/goodsinfo",

        data: {

            "goods_id": data_json.goods_id
        },
        dataType: "json",

        //async: "false",

        success: function (data) {

            var a = Object.assign(data, data_json);

            //console.log(data)

            if (data.codes == 200) {

                var html = template("OrderTpl", data);

                $("#order_body").html(html);

                defaultAddress(data_json.uid);//默认地址ַ

                if (isiphoneX) {

                    $("#order_footer").removeClass("order_footer_position");

                    $(".moneyDetail").css("margin-bottom", "0.427rem")

                } else {
                    $("#order_footer").addClass("order_footer_position")

                }

            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                        "VcData": "获取数据失败",
                        "VcWay": "ShowMessage"
                    });

                    //CallTerMinalListModel.jsCalliOSWithShowMessage("获取数据失败");

                } else if (isMobile == 0) {

                    window.android.toastMsg("获取数据失败");
                }
            }

            $(".date").html("日期：" + data.startTime.slice(5) + " ~ " + data.endTime.slice(5));     //日期

            var money = totalPrice.slice(1);                                                        //商品价格

            var sendTotal = Number($(".sendTotal").html());                                         //运费

            var nnn = $(".num").html().slice(3);                                                    //数量

            $(".cash_pledge").html(data_json.meal.goods_worth * nnn);

            var cash_pledge = Number(data_json.meal.goods_worth * nnn);                             //押金

            var couponPrice = Number($(".couponPrice").html()) || 0;                                //优惠券

            $(".order_price").html("实付款：￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));

            $(".order_address").on("click", function () {

                if (isMobile == 1) {

                    var message = {

                        "VcData": {

                            "contacts": contacts,

                            "iphone": iphone,

                            "addressTitle": address3,

                            "addressDetails": address2
                        },

                        "VcName": "AddressManager",

                        "VcWay": "AddAddress"
                    };

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage(message);


                } else if (isMobile == 0) {

                    var json = {

                        "contacts": contacts,

                        "iphone": iphone,

                        "address": address4,

                        "province": address2,

                        "city": address3
                    };

                    window.android.jumpToProjectAdress(JSON.stringify(json));
                }
            });
            //使用时间
            //$(".order_time .order_start").html(data.startTime);
            //$(".order_time .order_end").html(data.endTime);

            //$(".order_goodsMsg .confirmPrice").text((data.meal.data_type));                       //套餐

            $(".order_coupon").on("click",  function () {

                var json = {

                    "uid": data.uid,

                    "Tprice": data.money.slice(1),

                    "type": [10, 100]
                };

                if (isMobile == 1) {

                    var message = {

                        "VcData": json,

                        //"VcName": "FabricationDetails",

                        "VcWay": "OrderCoupons"
                    };

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage(message);


                } else if (isMobile == 0) {

                    window.android.showCoupon(JSON.stringify(json));
                }
            });

            var flag = true;

            $(".submit").on("touchstart", function () {

                var timeStart = data.startTime.replace(/-/g, "/");

                var timeEnd = data.endTime.replace(/-/g, "/");

                var timestampStart = Date.parse(new Date(timeStart)) / 1000; //开始时间

                var timestampEnd = Date.parse(new Date(timeEnd)) / 1000;     //结束时间

                var timestampNow = Date.parse(new Date()) / 1000;            //当前时间


                var timeLag = timestampEnd - timestampStart;

                var timeDistance = (mGetDate(1) + mGetDate(2) + mGetDate(3)) * 24 * 60 * 60;

                var length = $(".address_phone").html().length;


                if (flag && length > 0 && timestampNow < timestampStart && timeLag < timeDistance && timestampEnd > timestampStart) {

                    var cid;

                    if (useCoupon == 100) {

                        //cid = $(".order_coupon").attr("id");//优惠券id

                        ordermake(
                            data.uid,

                            $(".order_price").html().slice(5),

                            $(".address_contacts b").html(),

                            $(".address_phone").html(),

                            $(".serviceAddress b").html(),

                            useCoupon,

                            data.goods_id,

                            data.number,

                            timeFormatDate(timeStart),

                            timeFormatDate(timeEnd),

                            address,

                            data.meal.id,

                            token,

                            cid
                        );

                    } else if (useCoupon == 200) {

                        cid = $(".order_coupon").attr("id");//优惠券 id

                        ordermake(
                            data.uid,

                            $(".order_price").html().slice(5),

                            $(".address_contacts b").html(),

                            $(".address_phone").html(),

                            $(".serviceAddress b").html(),

                            useCoupon,

                            data.goods_id,

                            data.number,

                            timeFormatDate(timeStart),

                            timeFormatDate(timeEnd),

                            address,

                            data.meal.id,

                            token,

                            cid
                        );


                    }
                    flag = false;

                    setTimeout(function () {

                        flag = true;

                    }, 1000)

                } else {

                    if (timestampStart < timestampNow) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                                "VcData": "开始时间不能小于当前时间",
                                "VcWay": "ShowMessage"
                            });

                            //CallTerMinalListModel.jsCalliOSWithShowMessage("开始时间不能小于当前时间");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("开始时间不能小于当前时间");

                        }
                    } else if (timeLag > timeDistance) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                                "VcData": "结束时间不能大于开始时间的90天",
                                "VcWay": "ShowMessage"
                            });

                            //CallTerMinalListModel.jsCalliOSWithShowMessage("结束时间不能大于开始时间的90天");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("结束时间不能大于开始时间的90天");

                        }
                    } else if (timestampEnd < timestampStart) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                                "VcData": "结束时间不能小于开始时间",
                                "VcWay": "ShowMessage"
                            });

                            //CallTerMinalListModel.jsCalliOSWithShowMessage("结束时间不能小于开始时间");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("结束时间不能小于开始时间");

                        }
                    } else if (length <= 0) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                                "VcData": "服务地址不能为空",
                                "VcWay": "ShowMessage"
                            });

                            //CallTerMinalListModel.jsCalliOSWithShowMessage("服务地址不能为空");

                        } else if (isMobile == 0) {

                            window.android.toastMsg("服务地址不能为空");
                        }
                    }
                }

            });
            //协议
            //$(".xieyi").on("click", function () {
            //
            //    var json = {
            //
            //        "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",
            //
            //        "titleName": "用户租赁协议"
            //    };
            //
            //    if (isMobile == 1) {
            //
            //        var message = {
            //
            //            "VcData": json,
            //
            //            "VcName": "PublicWeb",
            //
            //            "VcWay": "PushVCName"
            //        };
            //
            //        window.webkit.messageHandlers.CallTerMinalListModel.postMessage(message);
            //
            //    } else if (isMobile == 0) {
            //
            //        window.android.toRule(JSON.stringify(json));
            //    }
            //});

        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallTerMinalListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    });
};

var address1 = "", address2 = "", address3 = "", address4 = "", contacts = "", contacts1 = "", iphone = "";

function receiveiOSAddAddress(a) {

    var result = JSON.parse(a);

    $(".serviceAddress b").html(result['shipping_address']);

    contacts = result['link_man'];

    $(".address_contacts b").html(result['link_man']);

    $(".address_phone").html(result['link_mobile']);

    iphone = result['link_mobile'];

    $(".address").css("margin-left", "0");

}

function receive_android_addAddress(k) {
    var result = JSON.parse(k);

    $(".serviceAddress b").html(result.province + result.city + result.district + result.address);

    address2 = result.province;

    address3 = result.city;

    address4 = result.address;

    contacts = result.contacts;

    $(".address_contacts b").html(result.contacts);

    $(".address_phone").html(result.iphone);

    iphone = result.iphone;

    $(".address").css("margin-left", "0");


}

function receiveiOSOrderCoupon(a) {

    var obj = $.parseJSON(a);

    if (obj) {

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.id);

        var money = totalPrice.slice(1);//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费


        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseFloat($(".insurance").html());// 保险

        var couponPrice = Number(obj.face) || 0;//优惠券

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));//�ܼ�

        $("b.couponMoney").html(couponPrice);

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");
    }
}

function receive_android_orderCoupon(k) {

    var obj = $.parseJSON(k);

    if (obj) {

        //alert(obj.cid);

        useCoupon = 200;

        $(".couponPrice").html(obj.face);

        $(".order_coupon").attr("id", obj.cid);

        var money = totalPrice.slice(1);//商品价格

        var sendTotal = Number($(".sendTotal").html());//运费

        var cash_pledge = Number($(".cash_pledge").html());//押金

        // var insurance = parseFloat($(".insurance").html());// 保险

        var couponPrice = Number(obj.face) || 0; //优惠券

        $(".couponMoney").html(couponPrice);//优惠金额

        $(".order_price").html("实付款:￥" + (Number(money) + sendTotal + cash_pledge - couponPrice));

    } else {

        useCoupon = 100;

        $(".couponPrice").html("请选择");
        // alert(useCoupon)
    }

}
//格式化时间
function timeFormatDate(timeStamp) {
    var tmpTime = Date.parse(new Date(timeStamp));
    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyyMMddhhmm');
}
//自取地址
function invite(uid) {

    $.ajax({

        type: "POST",

        url: url + "users/enterpriseinfo",

        dataType: "json",

        //anysc: false,

        data: {uid: uid},

        success: function (data) {

            //console.log(data)

            if (data.data.codes == "200") {

                $(".address_customer1").html(data.data.data.take_address);

                $(".address_contacts1").html(data.data.data.link_person);

                $(".address_phone1").html(data.data.data.link_mobile);
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallTerMinalListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    })
}
//下单
function ordermake(uid, total_money, receive_user_name, receive_user_mobile, receive_user_addr, useCoupon, goods_id, need_number, start_time, end_time, need_addr_id, meal_id, token, cid) {

    //alert(useCoupon + "--" + cid)

    $.ajax({

        type: "POST",

        url: url + "users/ordermake",

        dataType: "json",

        data: {

            "uid": uid,

            "total_money": total_money,

            "receive_user_name": receive_user_name,

            "receive_user_mobile": receive_user_mobile,

            "receive_user_addr": receive_user_addr,

            "use_coupon": useCoupon,

            "coupon_id": cid,

            "order_info": [

                {
                    "goods_id": goods_id,

                    "need_number": need_number,

                    "start_time": start_time,

                    "end_time": end_time,

                    "need_addr_id": need_addr_id,

                    "meal_id": meal_id,

                    "belong_model": 100
                }
            ]
        },

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            if (data.codes == "200") {

                //alert(data.data.order_code)

                if (isMobile == 1) {

                    var message = {

                        "VcData": {"order_code": data.data.order_code},

                        "VcName": "ListPay",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage(message);

                    //CallTerMinalListModel.jsCalliOSWithPushVCName({
                    //
                    //    "VcData": {"order_code": data.data.order_code},
                    //
                    //    "VcName": "ListPay"
                    //});

                } else if (isMobile == 0) {

                    window.android.jumptoOrderActivity(data.data.order_code);

                }
            } else if (data.codes != "200" && data.codes) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                        "VcData": data.msg,
                        "VcWay": "ShowMessage"
                    });

                    //CallTerMinalListModel.jsCalliOSWithShowMessage(data.msg);

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.msg);

                }
            } else if (data.codes == null) {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                        "VcData": "系统繁忙，请稍后重试",
                        "VcWay": "ShowMessage"
                    });

                    //CallTerMinalListModel.jsCalliOSWithShowMessage("系统繁忙，请稍后重试");

                } else if (isMobile == 0) {

                    window.android.toastMsg("系统繁忙，请稍后重试");
                }
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallTerMinalListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    });
}
function defaultAddress(uid) {

    $.ajax({

        url: url + "users/fourModel",

        type: "POST",

        dataType: "json",

        data: {
            "url": "address/lists",

            "uid": uid,

            "addr_type": 1
        },

        success: function (data) {

            //console.log(data);

            if (data.codes == 200) {

                var list = data.data.list[0];

                $(".address_contacts b").html(list.link_man);

                $(".address_phone").html(list.link_mobile);

                $(".serviceAddress b").html(list.shipping_address);


                //$(".order_address").attr("data-type", "100");

                $(".address").css("margin-left", 0)

            } else {

                $(".order_address").attr("data-type", "200");

                //$(".address .defultaddr").css("display","none");

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallTerMinalListModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallTerMinalListModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.getAndroidOrderId("请检查网络");
            }
        }
    });
}
//90天
function mGetDate(n) {

    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + n;

    if (month > 12) {

        year++;

        month = month - 12;
    }
    var d = new Date(year, month, 0);

    return d.getDate();
}

function ismobile() {
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1,
                presto: u.indexOf('Presto') > -1,
                webKit: u.indexOf('AppleWebKit') > -1,
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
                mobile: !!u.match(/AppleWebKit.*Mobile.*/),
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,
                iPhone: u.indexOf('iPhone') > -1,
                iPad: u.indexOf('iPad') > -1,
                webApp: u.indexOf('Safari') == -1,
                weixin: u.indexOf('MicroMessenger') > -1,
                qq: u.match(/\sQQ/i) == " qq"
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };
    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}

//var startDate;
//function receiveiOSOrderStart(a) {
//    startDate = $(".order_start").html(a);
//}
//function receive_android_startDate(k) {
//    startDate = $(".order_start").html(k);
//}
//var endDate;
//function receiveiOSOrderEnd(a) {
//    endDate = $(".order_end").html(a);
//}
//function receive_android_endDate(k) {
//    endDate = $(".order_end").html(k);
//}